package com.szsh.aiot.hsm.utils;

import com.szsh.aiot.common.utils.TimeTools;
import com.szsh.aiot.hsm.dao.ISubinfoSyncRet;
import com.szsh.aiot.hsm.dto.SubscribeSyncInfo;
import com.szsh.aiot.hsm.dto.enu.OrderSyncOpType;
import com.szsh.aiot.hsm.mapper.ISubinfoSyncRetMapper;
import com.szsh.aiot.hsm.thirdService.AbilityClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * B01增值业务平台同步
 *
 * @author zhangtt
 */
@Service
public class SubscribeInfoSyncProcess {
    private static final Logger LOGGER = LoggerFactory.getLogger(SubscribeInfoSyncProcess.class);
    private static final String SUCCESS_CODE = "0";

    @Autowired
    private AbilityClient abilityClient;
    @Autowired
    private ISubinfoSyncRetMapper subInfoSyncMapper;

    /**
     * 增值平台B01业务同步接口
     *
     * @param syncInfo 订阅信息
     */
    public void subscribeInfoSync(SubscribeSyncInfo syncInfo) {
        String broadband = syncInfo.getBroadband();
        String gatewayMac = syncInfo.getGatewayMac();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("用户[{}]，网关[{}]开始进行增值平台B01业务同步功能...", broadband, gatewayMac);
        }
        if (Objects.equals(OrderSyncOpType.SUB.getVal(), syncInfo.getOptype())) {
            // 如果没有就新增同步记录
            ifNullAddSyncRet(syncInfo);
            // 订购通知
            secOrderSync(syncInfo, "querySec-2");
            // 采集同步
            cameraOrderSync(syncInfo, "");
            // 上报同步
            vprovsetOrderSync(syncInfo, "orderVprovset-2");
        } else {
            cancelSync(syncInfo);
        }
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("用户[{}]，网关[{}]完成增值平台B01业务同步功能...", broadband, gatewayMac);
        }
    }

    /**
     * 查询是否存在同步记录，不存在则新增一条
     * @param syncInfo 订阅信息
     */
    private void ifNullAddSyncRet(SubscribeSyncInfo syncInfo) {
        try {
            String broadbandNO = syncInfo.getBroadband();
            String gatewayMac = syncInfo.getGatewayMac();
            ISubinfoSyncRet syncRet = subInfoSyncMapper.selectByBbn(broadbandNO, gatewayMac);
            if (syncRet != null) {
                return;
            }
            syncRet = new ISubinfoSyncRet();
            syncRet.setBroadbandNO(broadbandNO);
            syncRet.setGatewayMac(gatewayMac);
            subInfoSyncMapper.insert(syncRet);
        } catch (Exception e) {
            LOGGER.error("[{}]新增同步记录失败,", syncInfo.getBroadband(), e);
        }
    }

    /**
     * 订购同步，失败后发送指定的topic重试。成功则发送至查询队列
     *
     * @param syncInfo 订阅信息
     * @param topic    同步失败存入的topic
     */
    public void secOrderSync(SubscribeSyncInfo syncInfo, String topic) {
        // 获取同步记录
        ISubinfoSyncRet syncRet = getSyncRet(syncInfo);
        try{
            // 增值平台2.1同步接口
            String secResult = abilityClient.notifyOrderSec(syncInfo.getBroadband(), syncInfo.getGatewayMac());
            syncRet.setSecResult(secResult);
            if (secResult.startsWith(SUCCESS_CODE)) {
                // 2.3 查询接口
                String secResp = abilityClient.querySecConfig(syncInfo.getBroadband(), syncInfo.getGatewayMac());
                String[] secRespArr = secResp.split("\\|");
                syncRet.setSecConfigResult(secRespArr[0]);
                syncRet.setSecConfigResultDesc(secRespArr[1]);
                if (!secResp.startsWith(SUCCESS_CODE)) {
                    secOrderQuery(syncInfo,topic);
                }
            } else {
                if (!StringUtils.isEmpty(topic)) {
                    // 发送至同步接口重试
                  secOrderQuery(syncInfo,topic);
                } else {
                    // 发送至查询接口
                    secOrderQuery(syncInfo,"");
                 //   kafkaTemplate.send(KafkaTopic.QUERYSEC2, JsonConvert.object2str(syncInfo));
                }
            }
        }catch (Exception e){
            LOGGER.error("[{}]调用增值平台订购接口出错,",syncInfo.getBroadband(),e);
            syncRet.setSecConfigResult("-1");
            syncRet.setSecConfigResultDesc("调用增值平台订购接口返回失败");
        }
        subInfoSyncMapper.updateSecResult(syncRet);
    }

    /**
     * 订购查询，失败后重试
     *
     * @param syncInfo 订阅信息
     */
    public void secOrderQuery(SubscribeSyncInfo syncInfo, String topic) {
        String gatewayMac = syncInfo.getGatewayMac();
        String broadbandNO = syncInfo.getBroadband();
        // 获取同步记录
        ISubinfoSyncRet syncRet = subInfoSyncMapper.selectByBbn(broadbandNO, gatewayMac);
        if (syncRet == null) {
            LOGGER.error("用户[{}]同步记录不存在，不进行订购查询操作",broadbandNO);
            return;
        }
        // 增值平台2.3查询接口
        String secResp = abilityClient.querySecConfig(broadbandNO, gatewayMac);
        String[] secRespArr = secResp.split("\\|");
        syncRet.setSecConfigResult(secRespArr[0]);
        syncRet.setSecConfigResultDesc(secRespArr[1]);
        subInfoSyncMapper.updateSecResult(syncRet);
        if (!secResp.startsWith(SUCCESS_CODE)) {
            if (!StringUtils.isEmpty(topic)) {
                // 发送至同步接口重试
                //kafkaTemplate.send(topic, JsonConvert.object2str(syncInfo));
            }
        }
    }


    /**
     * 采集同步，失败后发送指定的topic重试。成功则发送至查询队列
     *
     * @param syncInfo 订阅信息
     * @param topic    同步失败存入的topic
     */
    public void cameraOrderSync(SubscribeSyncInfo syncInfo, String topic) {
        // 获取同步记录
        ISubinfoSyncRet syncRet = getSyncRet(syncInfo);
        try{
            // 增值平台2.4同步接口
            String cameraResult = abilityClient.notifyOrderSecCamera(syncInfo.getBroadband(), syncInfo.getGatewayMac());
            syncRet.setCameraResult(cameraResult);
            if (cameraResult.startsWith(SUCCESS_CODE)) {
                // 2.6 查询接口
                String cameraResp = abilityClient.queryCameraConfig(syncInfo.getBroadband(), syncInfo.getGatewayMac());
                String[] cameraRespArr = cameraResp.split("\\|");
                syncRet.setCameraConfigResult(cameraRespArr[0]);
                syncRet.setCameraConfigResultDesc(cameraRespArr[1]);
                if (!cameraResp.startsWith(SUCCESS_CODE)) {
                    // 发送至第二次查询接口
                   // kafkaTemplate.send(KafkaTopic.QUERYSECCAMERA2, JsonConvert.object2str(syncInfo));
                    cameraOrderQuery(syncInfo,topic);
                }
            } else {
                if (!StringUtils.isEmpty(topic)) {
                    // 发送至同步接口重试
                   // kafkaTemplate.send(topic, JsonConvert.object2str(syncInfo));
                    cameraOrderSync(syncInfo,topic);
                } else {
                    // 发送至第二次查询接口
                   // kafkaTemplate.send(KafkaTopic.QUERYSECCAMERA2, JsonConvert.object2str(syncInfo));
                    cameraOrderQuery(syncInfo,"");
                }
            }
        }catch (Exception e){
            LOGGER.error("[{}]调用增值平台采集接口出错,",syncInfo.getBroadband(),e);
            syncRet.setCameraConfigResult("-1");
            syncRet.setCameraConfigResultDesc("调用增值平台采集接口返回失败");
        }
        subInfoSyncMapper.updateCameraResult(syncRet);
    }

    /**
     * 采集查询，失败后重试
     *
     * @param syncInfo 订阅信息
     */
    public void cameraOrderQuery(SubscribeSyncInfo syncInfo, String topic) {
        String gatewayMac = syncInfo.getGatewayMac();
        String broadbandNO = syncInfo.getBroadband();
        // 获取同步记录
        ISubinfoSyncRet syncRet = subInfoSyncMapper.selectByBbn(broadbandNO, gatewayMac);
        if (syncRet == null) {
            LOGGER.error("用户[{}]同步记录不存在，不进行采集查询操作",broadbandNO);
            return;
        }
        // 2.6 查询接口
        String cameraResp = abilityClient.queryCameraConfig(broadbandNO, gatewayMac);
        String[] cameraRespArr = cameraResp.split("\\|");
        syncRet.setCameraConfigResult(cameraRespArr[0]);
        syncRet.setCameraConfigResultDesc(cameraRespArr[1]);
        // 更新结果
        subInfoSyncMapper.updateCameraResult(syncRet);
        /*if (!cameraResp.startsWith("0")) {
            if (!StringUtils.isEmpty(topic)) {
                // 发送至同步接口重试
                kafkaTemplate.send(topic, JsonConvert.object2str(syncInfo));
            }
        }*/
    }

    /**
     * 上报同步，失败后发送指定的topic重试。成功则发送至查询队列
     *
     * @param syncInfo  订阅信息
     * @param topic     同步失败存入的topic
     */
    public void vprovsetOrderSync(SubscribeSyncInfo syncInfo, String topic) {
        // 获取同步记录
        ISubinfoSyncRet syncRet = getSyncRet(syncInfo);
        try{
            // 增值平台2.7同步接口
            List<String> gateWays = new ArrayList<String>();
            if (StringUtils.isNotBlank(syncInfo.getGatewayMac())){
                gateWays.add(syncInfo.getGatewayMac());
            }

            String result = abilityClient.notifyOrderVprovset(syncInfo.getBroadband(), gateWays);
            syncRet.setVprovsetResult(result);
            if (result.startsWith(SUCCESS_CODE)) {
                // 2.9 上报查询
                String vprovsetResp = abilityClient.queryVprovsetConfig(syncInfo.getBroadband(), gateWays);
                String[] vprovsetRespArr = vprovsetResp.split("\\|");
                syncRet.setVprovsetConfigResult(vprovsetRespArr[0]);
                syncRet.setVprovsetConfigResultDesc(vprovsetRespArr[1]);
                if (!vprovsetResp.startsWith(SUCCESS_CODE)) {
                    // 发送至第二次查询接口
                   // kafkaTemplate.send(KafkaTopic.QUERYVPROVSET2, JsonConvert.object2str(syncInfo));
                    vprovsetOrderQuery(syncInfo,"");
                }
            } else {
                if (!StringUtils.isEmpty(topic)) {
                    // 发送至同步接口重试
                   // kafkaTemplate.send(topic, JsonConvert.object2str(syncInfo));
                    vprovsetOrderSync(syncInfo,"");
                } else {
                    // 发送至第二次查询接口
                   // kafkaTemplate.send(KafkaTopic.QUERYVPROVSET2, JsonConvert.object2str(syncInfo));
                    vprovsetOrderQuery(syncInfo,"");
                }
            }
        }catch (Exception e){
            LOGGER.error("[{}]调用增值平台上报接口出错,",syncInfo.getBroadband(),e);
            syncRet.setVprovsetConfigResult("-1");
            syncRet.setVprovsetConfigResultDesc("调用增值平台上报接口返回失败");
        }
        subInfoSyncMapper.updateVprovsetResult(syncRet);
    }

    /**
     * 上报查询，失败后重试
     *
     * @param syncInfo  订阅信息
     */
    public void vprovsetOrderQuery(SubscribeSyncInfo syncInfo, String topic) {
        String gatewayMac = syncInfo.getGatewayMac();
        String broadbandNO = syncInfo.getBroadband();
        // 获取同步记录
        ISubinfoSyncRet syncRet = subInfoSyncMapper.selectByBbn(broadbandNO, gatewayMac);
        if (syncRet == null) {
            LOGGER.error("用户[{}]同步记录不存在，不进行查询操作",broadbandNO);
            return;
        }

        List<String> gateWays = new ArrayList<String>();
        if (StringUtils.isNotBlank(syncInfo.getGatewayMac())){
            gateWays.add(syncInfo.getGatewayMac());
        }

        // 2.9 查询接口
        String vprovsetResp = abilityClient.queryVprovsetConfig(broadbandNO,gateWays);
        String[] vprovsetRespArr = vprovsetResp.split("\\|");
        syncRet.setVprovsetConfigResult(vprovsetRespArr[0]);
        syncRet.setVprovsetConfigResultDesc(vprovsetRespArr[1]);
        // 更新结果
        subInfoSyncMapper.updateVprovsetResult(syncRet);
        /*if (!vprovsetResp.startsWith(SUCCESS_CODE)) {
            if (!StringUtils.isEmpty(topic)) {
                // 发送至同步接口重试
                kafkaTemplate.send(topic, JsonConvert.object2str(syncInfo));
            }
        }*/
    }

    /**
     * 退订同步
     * @param syncInfo 订阅信息
     */
    public void cancelSync(SubscribeSyncInfo syncInfo) {
        String gatewayMac = syncInfo.getGatewayMac();
        String broadbandNO = syncInfo.getBroadband();

        List<String> gateWays = new ArrayList<String>();
        if (StringUtils.isNotBlank(syncInfo.getGatewayMac())){
            gateWays.add(syncInfo.getGatewayMac());
        }
        // 增值平台2.2
        String secResult = abilityClient.notifyCancelSec(broadbandNO, gatewayMac);
        // 增值平台2.5
        String secCameraResult = abilityClient.notifyCancelSecCamera(broadbandNO, gatewayMac);
        // 增值平台2.8
        String vprovsetResult = abilityClient.notifyCancelVprovset(broadbandNO, gateWays);

        if (StringUtils.startsWith(secResult, SUCCESS_CODE)
                && StringUtils.startsWith(secCameraResult, SUCCESS_CODE)
                && StringUtils.startsWith(vprovsetResult, SUCCESS_CODE)) {
            // 全部取消成功
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("用户[{}],网关[{}],退订成功.", broadbandNO, gatewayMac);
            }
            subInfoSyncMapper.deleteByBroadbandNoAndGateWayMac(broadbandNO, gatewayMac);
        } else {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("用户[{}],网关[{}],退订失败{}.", broadbandNO, gatewayMac,
                        String.format("(%s:%s).(%s)(%s)(%s)", broadbandNO, gatewayMac, secResult, secCameraResult, vprovsetResult));
            }
        }
    }

    /**
     * 获取同步对象
     *
     * @param syncInfo 订阅信息
     * @return 同步记录
     */
    private ISubinfoSyncRet getSyncRet(SubscribeSyncInfo syncInfo) {
        String broadbandNO = syncInfo.getBroadband();
        String gatewayMac = syncInfo.getGatewayMac();
        ISubinfoSyncRet syncRet = subInfoSyncMapper.selectByBbn(broadbandNO, gatewayMac);
        if (syncRet == null) {
            syncRet = new ISubinfoSyncRet();
            syncRet.setBroadbandNO(broadbandNO);
            syncRet.setGatewayMac(gatewayMac);
            subInfoSyncMapper.insert(syncRet);
        }
        syncRet.setBatchID(syncInfo.getBatchID());
        syncRet.setSyncTime(TimeTools.getNow());
        return syncRet;
    }
}
